package com.xiaojie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.hash.BloomFilter;
import com.xiaojie.annotation.DataCode;
import com.xiaojie.entity.ActionScope;
import com.xiaojie.entity.User;
import com.xiaojie.entity.UserQuery;
import com.xiaojie.mapper.UserMapper;
import com.xiaojie.service.UserService;
import com.xiaojie.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @author: xiaojie
 * @date: 2021.09.08
 */
@Service
public class UserServiceImpl implements UserService {
    private static final String  USERKEY="USER-KEY";
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;
    //定义布隆过滤器
    private static BloomFilter<String> namesBloomFilter = null;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public User getUserByName(String name) {
        //判断布隆过滤器是否含有该数据
//        if(!namesBloomFilter.mightContain(name)){
//            //如果不存在该数据直接返回，而不进行数据库查询
//            return null;
//        }
        JSONObject obj= (JSONObject) redisUtil.get(USERKEY + ":" + name);
        if (null==obj){
            System.out.println("缓存中没有该值,查询数据库");
            User resultUser = userMapper.selectByName(name);
            redisTemplate.opsForValue().set("user",resultUser);
//            if (null!= resultUser) {
//                redisUtil.set(USERKEY+":"+resultUser.getName(), JSONObject.toJSON(resultUser),60);
//                return resultUser;
//            }
        }
        User user = JSONObject.toJavaObject(obj,User.class);
        return user;
    }

    @Override
//    @Cacheable(cacheNames = "users", key = "'getListUsers'")
    public List<User> getUSerList() {
        System.out.println(Thread.currentThread().getName());
        return userMapper.selectAll();
    }

    @Override
    public void preBlongData() {
        List<User> users = userMapper.selectAll();
        for (User user:users){
            namesBloomFilter.put(user.getName());
        }
    }

    @Override
    @DataCode(type = DataCode.Type.USER,name="#scope.name",scope="#scope.scope",shopCode = "#scope.shopCode")
    public List<User> list(UserQuery query, ActionScope scope) {
        PageHelper.startPage(1, 2);
        List<User> list = userMapper.list(query);
        return list;
    }
}
